package com.dkd.manage.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.constant.DkdContants;
import com.dkd.common.core.domain.entity.SysUser;
import com.dkd.common.utils.SecurityUtils;
import com.dkd.manage.domain.VendingMachine;
import com.dkd.manage.service.IVendingMachineService;
import com.dkd.system.service.ISysRoleService;
import com.dkd.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.manage.domain.Emp;
import com.dkd.manage.service.IEmpService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import static com.dkd.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 员工列表Controller
 *
 * @author 赵昊鹏
 * @date 2024-10-10
 */
@RestController
@RequestMapping("/manage/emp")
public class EmpController extends BaseController
{
    @Autowired
    private IEmpService empService;

    @Autowired
    private ISysUserService userService; // 注入用户服务

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IVendingMachineService vendingMachineService;
    /**
     * 查询员工列表列表
     */
    @PreAuthorize("@ss.hasPermi('manage:emp:list')")
    @GetMapping("/list")
    public TableDataInfo list(Emp emp)
    {
        startPage();
        List<Emp> list = empService.selectEmpList(emp);
        return getDataTable(list);
    }

    /**
     * 导出员工列表列表
     */
    @PreAuthorize("@ss.hasPermi('manage:emp:export')")
    @Log(title = "员工列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Emp emp)
    {
        List<Emp> list = empService.selectEmpList(emp);
        ExcelUtil<Emp> util = new ExcelUtil<Emp>(Emp.class);
        util.exportExcel(response, list, "员工列表数据");
    }

    /**
     * 获取员工列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:emp:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(empService.selectEmpById(id));
    }

    /**
     * 新增员工列表
     * @param emp
     * @return
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('manage:emp:add')")
    @Log(title = "员工列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Emp emp) {
        // 1. 添加员工
        int result = empService.insertEmp(emp);

        if (result > 0) {
            // 2. 如果员工添加成功，则添加用户
            SysUser user = new SysUser();
            String pinyinUsername = toPinyin(emp.getUserName()); // 转换为拼音
            user.setUserName(pinyinUsername); // 设置用户名为拼音
            user.setPassword(SecurityUtils.encryptPassword("123456")); // 设置初始密码
            user.setNickName(emp.getUserName()); // 设置用户昵称
            user.setDeptId(100L); // 默认部门 ID 为100
            user.setAvatar(emp.getImage()); // 设置头像
            user.setStatus(emp.getStatus().toString()); // 设置状态
            user.setPhonenumber(emp.getMobile()); // 设置手机号码
            user.setRemark("自动创建"); // 备注
            user.setCreateBy(getUsername()); // 设置创建者
            Long roleId = roleService.selectRoleIdByName(emp.getRoleName());
            user.setRoleId(roleId); // 设置角色
            user.setRoleIds(new Long[]{roleId}); // 设置角色集合

            // 3. 调用用户服务添加用户并获取用户 ID
            SysUser createdUser = userService.insertUser2(user);
            if (createdUser != null) {
                emp.setUserId(createdUser.getUserId()); // 设置用户 ID
                empService.updateEmp(emp); // 更新员工信息
                return toAjax(result);
            } else {
                return error("用户创建失败");
            }
        }
        return error("员工创建失败");
    }

    /**
     * 修改员工列表
     * @param emp
     * @return
     */

    @Transactional
    @PreAuthorize("@ss.hasPermi('manage:emp:edit')")
    @Log(title = "员工列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Emp emp) {
        // 更新员工信息
        int result = empService.updateEmp(emp);

        // 更新用户信息
        if (result > 0) {
            SysUser user = userService.selectUserById(emp.getUserId());
            if (user != null) {
                String pinyinUsername = toPinyin(emp.getUserName()); // 转换为拼音
                user.setUserName(pinyinUsername); // 设置用户名为拼音
                user.setNickName(emp.getUserName());
                user.setAvatar(emp.getImage());
                user.setStatus(emp.getStatus().toString());
                user.setPhonenumber(emp.getMobile());
                user.setRoleId(roleService.selectRoleIdByName(emp.getRoleName()));
                user.setRoleIds(new Long[]{user.getRoleId()});

                userService.updateUser(user); // 更新用户
            }
            return toAjax(result);
        }
        return error("员工更新失败");
    }

    @Transactional
    @PreAuthorize("@ss.hasPermi('manage:emp:remove')")
    @Log(title = "员工列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 删除员工并同步删除用户
        for (Long id : ids) {
            Emp emp = empService.selectEmpById(id);
            if (emp != null) {
                userService.deleteUserById(emp.getUserId()); // 删除对应用户
            }
        }
        return toAjax(empService.deleteEmpByIds(ids));
    }

    /**
     * 查询运营人员列表
     * @param innerCode
     * @return
     */
    @PreAuthorize("@ss.hasPermi('manage:emp:list')")
    @GetMapping("/businessList/{innerCode}")
    public AjaxResult businessList(@PathVariable("innerCode") String innerCode)
    {
        if(innerCode == null)
        {
            return error("售货机不存在");
        }
        //1.根据innerCode 查询售货机信息
        VendingMachine vendingMachine = vendingMachineService.selectVendingMachineByInnerCode(innerCode);
        //根据区域id、员工编号、员工状态查询运维人员列表
        Emp emp = new Emp();
        emp.setRegionId(vendingMachine.getRegionId());//根据售货机区域id设置查询的员工区域id
        emp.setRoleCode(DkdContants.ROLE_CODE_BUSINESS);//设置查询为运营人员
        emp.setStatus(DkdContants.EMP_STATUS_NORMAL);//设置查询为正常状态
        return success(empService.selectEmpList(emp));
    }
    /**
     * 查询运维员工列表
     * @param innerCode
     * @return
     */
    @PreAuthorize("@ss.hasPermi('manage:emp:list')")
    @GetMapping("/operationList/{innerCode}")
    public AjaxResult operationList(@PathVariable("innerCode") String innerCode)
    {
        if(innerCode == null)
        {
            return error("售货机不存在");
        }
        //1.根据innerCode 查询售货机信息
        VendingMachine vendingMachine = vendingMachineService.selectVendingMachineByInnerCode(innerCode);
        //根据区域id、员工编号、员工状态查询运维人员列表
        Emp emp = new Emp();
        emp.setRegionId(vendingMachine.getRegionId());//根据售货机区域id设置查询的员工区域id
        emp.setRoleCode(DkdContants.ROLE_CODE_OPERATOR);//设置查询为运维人员
        emp.setStatus(DkdContants.EMP_STATUS_NORMAL);//设置查询为正常状态
        return success(empService.selectEmpList(emp));
    }

    /**
     * 员工签到功能
     */
    @Log(title = "员工签到", businessType = BusinessType.UPDATE)
    @PostMapping("/sign")
    public AjaxResult sign(@RequestBody Map<String, Long> params) {
        Long userId = params.get("userId");
        log.info("签到接口接收到的userId: {}", userId);
        if (userId == null) {
            return error("用户ID不能为空");
        }
        return empService.sign(userId);
    }

    /**
     * 检测某员工今天签到状态
     */
    @PostMapping("/signStatus")
    public int signStatus(@RequestBody Map<String, Long> params) {
        Long userId = params.get("userId");
        log.info("签到状态接口接收到的userId: {}", userId);
        if (userId == null) {
            return 0; // 未签到状态
        }
        return empService.signStatus(userId);
    }

    /**
     * 员工签到统计
     */
    @PostMapping("/signCount")
    public AjaxResult signCount(@RequestBody Map<String, Long> params) {
        Long userId = params.get("userId");
        log.info("签到统计接口接收到的userId: {}", userId);
        if (userId == null) {
            return error("用户ID不能为空");
        }
        return empService.signCount(userId);
    }

    /**
     * 员工签到排行
     */
    @PostMapping("/signRank")
    public AjaxResult signRank() {
        return empService.signRank();
    }

    private String toPinyin(String chinese) {
        StringBuilder pinyinStr = new StringBuilder();
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char c : newChar) {
            if (c > 128) {
                try {
                    pinyinStr.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr.append(c);
            }
        }
        return pinyinStr.toString();
    }
}
